//验证今天是星期几，输出为工作日或者周末
function whatToday(date) {
    date = date.split("-");
    date = new Date(date[0], parseInt(date[1] - 1), date[2]);
    if (date.getDay() >= 1 && date.getDay() <= 5) {
        return "workday";
    } else {
        return "weekend";
    }
}

//验证时间是否冲突如果冲突返回true不冲突返回false
//传入的参数为数组和字符串 ["9:00~12:00","13:00~15:00"],"13:00~15:00"
function checkConflictsTime(usedTime, time) {
    time = time.split("~");
    let firstTime = parseInt(time[0]);
    let lastTime = parseInt(time[1]);
    for (let i = 0; i < usedTime.length; i++) {
        let usedfirst = parseInt(usedTime[i].split("~")[0]);
        let usedlast = parseInt(usedTime[i].split("~")[1]);
        if (lastTime <= usedfirst || firstTime >= usedlast) {
            if (i === (usedTime.length - 1)) {
                return false;
            }
        } else {
            return true;
        }
    }
}
//写入数据的主函数
// 如果时间冲突返回字符串，如果不冲突返回用户的预定需求对象
function writeData(customerList, customerNeed) {
    let user = customerNeed["user"];
    let date = customerNeed["date"];
    let time = customerNeed["time"];
    let space = customerNeed["space"];
    if (customerList.hasOwnProperty(space) && customerList[space].hasOwnProperty(date)) {
        if (!checkConflictsTime(customerList[space][date]["usedTime"], time)) {
            customerList[space][date]["usedTime"].push(time);
            if (customerList[space][date].hasOwnProperty(user)) {
                customerList[space][date][user].push(time);
            } else {
                customerList[space][date][user] = [time];
            }
            return customerList;
        } else {
            return "Error: the booking conflicts with existing bookings!";
        }
    } else {
        customerList[space][date] = {
            "today": whatToday(date),
            "usedTime": [time],
            [user]: [time]
        };
        return customerList;
    }
}

module.exports.writeData = writeData;